import React from 'react';
import CountDown from '@/components/countown';
import type business from '@/types/business';

const Emails = () => {
    const [form] = React.UI.Form.useForm();
    const [business] = useState<business>(React.business);

    if (business.auth === "1") {
        React.success('您已认证，无需重复认证');
        React.navigate('/business');
    }

    const EmailFinish = async () => {
        const result = await React.Http.post('/Business/email', {
            id: business.id,
            email: form.getFieldValue('email'),
            action: 'check',
            code: form.getFieldValue('code')
        })

        if (result.code === 1) {
            React.success('邮箱认证成功');
            React.navigate('/business');
        } else {
            React.fail('邮箱认证失败');
        }
    }

    const SendEmail = async () => {
        const result = await React.Http.post('/Business/email', {
            id: business.id,
            email: form.getFieldValue('email'),
            action: 'send'
        })

        if (result.code === 1) {
            React.success('验证码发送成功');
        } else {
            React.fail('验证码发送失败');
        }
    }


    return (
        <>
            <React.UI.Form
                form={form}
                onFinish={EmailFinish}
                layout="horizontal"
                footer={
                    <React.UI.Button block type="submit" color="primary" size="large">
                        提交
                    </React.UI.Button>
                }
            >
                <React.UI.Form.Item
                    initialValue={business.email}
                    rules={[
                        { required: true, message: "请填写正确的邮箱" },
                        { type: "email", warningOnly: true },
                    ]}
                    name="email"
                    label="邮箱"
                >
                    <React.UI.Input placeholder="请输入邮箱" />
                </React.UI.Form.Item>

                <React.UI.Form.Item
                    label="邮箱验证码"
                    extra={
                        <CountDown
                            initialSeconds={10}
                            buttonTextBefore="发送验证码"
                            SendEmail={SendEmail}
                        />
                    }
                    name="code"
                    rules={[{ required: true, message: "验证码不能为空" }]}
                >
                    <React.UI.Input placeholder="请输入邮箱验证码" />
                </React.UI.Form.Item>
            </React.UI.Form>
        </>
    )
}

export default Emails;